package com.ken.common.utils;

import cn.hutool.core.io.FileUtil;

import java.io.*;
import java.util.concurrent.TimeUnit;
import javazoom.jl.decoder.Bitstream;
import javazoom.jl.decoder.Decoder;
import javazoom.jl.decoder.Header;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.decoder.SampleBuffer;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;

public class AudioConverterUtil {
//    public static File convertToMP3(File inputFile) throws IOException, InterruptedException {
//        if (!inputFile.exists()) {
//            throw new IllegalArgumentException("输入文件不存在");
//        }
//
//        // 生成临时文件路径
//        String outputFilePath = System.getProperty("java.io.tmpdir") + File.separator + "output.mp3";
//        File outputFile = new File(outputFilePath);
//
//        // 构建FFmpeg命令
//        String ffmpegCommand = String.format("ffmpeg -y -i \"%s\" -q:a 0 \"%s\"", inputFile.getAbsolutePath(), outputFile.getAbsolutePath());
//
//        // 执行FFmpeg命令
//        Process process = Runtime.getRuntime().exec(ffmpegCommand);
//        process.waitFor();
//
//        // 检查转换结果
//        if (!outputFile.exists()) {
//            throw new IOException("转换失败，无法生成MP3文件");
//        }
//
//        return outputFile;
//    }
public static File convertToMP3(File inputFile) throws IOException, InterruptedException {
    if (!inputFile.exists()) {
        throw new IllegalArgumentException("输入文件不存在");
    }

    // 生成临时文件路径
    String tempOutputFilePath = System.getProperty("java.io.tmpdir") + File.separator + "output.mp3";
    File tempOutputFile = new File(tempOutputFilePath);

    // 构建FFmpeg命令，添加 -y 参数以自动确认覆盖文件
    String ffmpegCommand = String.format("ffmpeg -y -i \"%s\" -q:a 0 \"%s\"", inputFile.getAbsolutePath(), tempOutputFile.getAbsolutePath());

    // 执行FFmpeg命令
    Process process = Runtime.getRuntime().exec(ffmpegCommand);

    // 读取标准输出和错误输出
    BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
    BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));

    // 创建一个线程读取标准输出
    Thread outputThread = new Thread(() -> {
        String s;
        try {
            while ((s = stdInput.readLine()) != null) {
                System.out.println(s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    });

    // 创建一个线程读取错误输出
    Thread errorThread = new Thread(() -> {
        String s;
        try {
            while ((s = stdError.readLine()) != null) {
                System.err.println(s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    });

    // 启动输出和错误输出读取线程
    outputThread.start();
    errorThread.start();

    // 等待进程完成，设置超时时间为60秒
    if (!process.waitFor(60, TimeUnit.SECONDS)) {
        // 超时处理
        process.destroy();
        throw new InterruptedException("FFmpeg进程超时");
    }

    // 等待输出和错误输出线程结束
    outputThread.join();
    errorThread.join();

    // 检查转换结果
    if (!tempOutputFile.exists()) {
        throw new IOException("转换失败，无法生成MP3文件");
    }

    return tempOutputFile;
}
    public static File convertToPCM(File inputFile) throws IOException, InterruptedException {
        if (!inputFile.exists()) {
            throw new IllegalArgumentException("输入文件不存在");
        }

        // 生成临时文件路径
        String tempOutputFilePath = System.getProperty("java.io.tmpdir") + File.separator + "output.pcm";
        File tempOutputFile = new File(tempOutputFilePath);

        // 构建FFmpeg命令，添加 -y 参数以自动确认覆盖文件
        String ffmpegCommand = String.format("ffmpeg -y -i \"%s\" -f s16le -acodec pcm_s16le \"%s\"", inputFile.getAbsolutePath(), tempOutputFile.getAbsolutePath());

        // 执行FFmpeg命令
        Process process = Runtime.getRuntime().exec(ffmpegCommand);

        // 读取标准输出和错误输出
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
        BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));

        // 创建一个线程读取标准输出
        Thread outputThread = new Thread(() -> {
            String s;
            try {
                while ((s = stdInput.readLine()) != null) {
                    System.out.println(s);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

        // 创建一个线程读取错误输出
        Thread errorThread = new Thread(() -> {
            String s;
            try {
                while ((s = stdError.readLine()) != null) {
                    System.err.println(s);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

        // 启动输出和错误输出读取线程
        outputThread.start();
        errorThread.start();

        // 等待进程完成，设置超时时间为60秒
        if (!process.waitFor(60, TimeUnit.SECONDS)) {
            // 超时处理
            process.destroy();
            throw new InterruptedException("FFmpeg进程超时");
        }

        // 等待输出和错误输出线程结束
        outputThread.join();
        errorThread.join();

        // 检查转换结果
        if (!tempOutputFile.exists()) {
            throw new IOException("转换失败，无法生成PCM文件");
        }

        return tempOutputFile;
    }
    public static File convertMp3ToPcm(File inputFile) throws IOException {
        // 创建临时文件保存转换后的PCM文件
        File outputPcmFile = File.createTempFile("converted-", ".pcm");
        outputPcmFile.deleteOnExit(); // 确保程序退出时删除临时文件

        ProcessBuilder processBuilder = new ProcessBuilder(
                "ffmpeg",
                "-y",
                "-i", inputFile.getAbsolutePath(),
                "-ac", "1",
                "-ar", "16000",
                "-f", "s16le",
                outputPcmFile.getAbsolutePath()
        );

        processBuilder.redirectErrorStream(true);
        try {
            Process process = processBuilder.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            int exitCode = process.waitFor();
            if (exitCode == 0) {
                System.out.println("Conversion completed successfully.");
                return outputPcmFile; // 返回临时PCM文件
            } else {
                System.out.println("Conversion failed with exit code " + exitCode);
                return null; // 转换失败返回null
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            return null; // 捕获异常时返回null
        }
    }
}
